package com.kefu.exam.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.call.mapper.ActivityInventoryInfoMapper;
import com.kefu.call.model.ActivityInventoryInfo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.util.JacksonUtil;
import com.kefu.exam.mapper.*;
import com.kefu.exam.model.*;
import com.kefu.exam.vo.*;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.kefu.common.service.AbstractKefuService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xy
 * @date 2022/02/28
 */
@Service
public class ExamPaperAnswerService extends AbstractKefuService<ExamPaperAnswer> {
    @Resource
    protected ExamPaperMapper examPaperMapper;
    @Resource
    protected ExamPaperAnswerMapper examPaperAnswerMapper;
    @Resource
    protected ActivityInventoryInfoMapper activityInventoryInfoMapper;
    @Resource
    protected ExamPaperAnswerService examPaperAnswerService;
    @Resource
    protected ExamSubjectAnswerMapper examSubjectAnswerMapper;
    @Resource
    private ExamSubjectMapper examSubjectMapper;
    @Resource
    private ExamCascadeJumpMapper examCascadeJumpMapper;
    @Resource
    private ExamPaperSubjectMapper examPaperSubjectMapper;


    public String addPaperAnswer(ExamPaperAnswerInsertVo examCardAnswerVo) {
        ExamPaperAnswer info = examCardAnswerVo.convert();
        int i = examPaperAnswerMapper.insert(info);
        logger.info("添加客户答案[{}]:{}", i, JacksonUtil.toString(info));
        return info.getPaperId();
    }


    public String batchSubmit(ExamPaperAnswerBatchSubmitVo batchSubmitVo) {
        //插入前将已经有的全部删除
        examPaperAnswerMapper.delete(Wrappers.lambdaQuery(ExamPaperAnswer.class)
                .eq(ExamPaperAnswer::getPartnerId, batchSubmitVo.getPartnerId()));

        /**
         * 清单信息
         */
        ActivityInventoryInfo info = activityInventoryInfoMapper.selectByPrimaryKey(batchSubmitVo.getPartnerId());
        if (Objects.isNull(info)) {
            throw BusinessException.msg("拨打清单查询失败");
        }
        /**
         * 问卷信息
         */
        ExamPaper examPaper = examPaperMapper.selectByPrimaryKey(batchSubmitVo.getPaperId());
        if (Objects.isNull(examPaper)) {
            throw BusinessException.msg("问卷查询失败");
        }
        // 问卷是否做了一道题
        if (null == batchSubmitVo.getSubjectAnswerRelVoList() || batchSubmitVo.getSubjectAnswerRelVoList().size() == 0) {
            throw BusinessException.msg("问卷填写不能为空");
        }
        KefuContext context = KefuContext.getKefuContext();
        List<SubjectAnswerRelVo> subjectAnswerRelVoList = batchSubmitVo.getSubjectAnswerRelVoList();
        for (SubjectAnswerRelVo item : subjectAnswerRelVoList) {
            ExamPaperAnswer obj = new ExamPaperAnswer();
            obj.setPaperId(examPaper.getPaperId());
            obj.setPartnerId(batchSubmitVo.getPartnerId());
            obj.setSubjectId(item.getSubjectId());
            obj.setAnswerId(item.getAnswerId());
            obj.setAnswerContent(item.getAnswerContent());
            obj.setCreateTime(context.getNow());
            obj.setCreateUser(context.getUserId());
            obj.setCreateName(context.getUserName());
            int i = examPaperAnswerMapper.insert(obj);
            logger.info("批量回答问卷，保存题目回答信息[{}]:{}", i, JacksonUtil.toString(obj));
        }
        return batchSubmitVo.getPaperId();
    }

    //partnerId拨打清单的ID

    public List<ExamPaperAnswerVo> getActivityPaperInfo(String partnerId) {
        JoinLambdaWrapper<ExamPaperAnswer> wrapper = joinLambdaQueryWrapper(ExamPaperAnswer.class);
        wrapper.select(ExamPaperAnswer::getSubjectId, ExamPaperAnswer::getAnswerContent)
                .eq(ExamPaperAnswer::getPartnerId, partnerId)
                .leftJoin(ExamSubject.class, ExamSubject::getSubjectId, ExamPaperAnswer::getSubjectId)
                .select(ExamSubject::getTypeName, ExamSubject::getSubjectContent,ExamSubject::getFatherSubject)
                .and(w -> {
                    w.eq(ExamSubject::getFatherSubject, "")
                            .or()
                            .isNull(ExamSubject::getFatherSubject);
                })
                .end();
        String paperId = "";
        List<ExamPaperAnswerVo> list = examPaperAnswerService.joinList(wrapper, ExamPaperAnswerVo.class);
        list = list.stream().distinct().collect(Collectors.toList());
        for (ExamPaperAnswerVo answerVo : list) {
            List<ExamPaperAnswer> paperAnswerList = examPaperAnswerMapper.selectList(Wrappers.lambdaQuery(ExamPaperAnswer.class)
                    .eq(ExamPaperAnswer::getSubjectId, answerVo.getSubjectId())
                    .eq(ExamPaperAnswer::getPartnerId, partnerId));
            List<String> answerIds = new ArrayList<>();
            for (ExamPaperAnswer examPaperAnswer : paperAnswerList) {
                answerIds.add(examPaperAnswer.getAnswerId());
                if (paperId.equals("")) {
                    paperId = examPaperAnswer.getPaperId();
                }
            }
            answerVo.setAnswerId(answerIds);
        }

        for (ExamPaperAnswerVo examPaperAnswerVo : list) {
            String subjectId = examPaperAnswerVo.getSubjectId();
            List<ExamSubjectAnswer> examSubjectAnswers = (examSubjectAnswerMapper.selectList(Wrappers.lambdaQuery(ExamSubjectAnswer.class)
                    .select(ExamSubjectAnswer::getAnswerId, ExamSubjectAnswer::getAnswerContent)
                    .eq(ExamSubjectAnswer::getSubjectId, subjectId)
                    .orderByAsc(ExamSubjectAnswer::getAnswerSort)
            ));
            List<ExamCascadeJump> examCascadeJumpList = examCascadeJumpMapper.selectList(Wrappers.lambdaQuery(ExamCascadeJump.class)
                    .eq(ExamCascadeJump::getTenantId, KefuContext.getKefuContext().getTenantId())
                    .eq(ExamCascadeJump::getPaperId, paperId));
            List<ExamPaperSubject> examPaperSubjectList = examPaperSubjectMapper.selectList(Wrappers.lambdaQuery(ExamPaperSubject.class)
                    .eq(ExamPaperSubject::getPaperId, paperId));
            List<ExamSubjectAnswerVo> examSubjectAnswerVoList = Lists.newArrayList();
            for (ExamSubjectAnswer examSubjectAnswer : examSubjectAnswers) {
                ExamSubjectAnswerVo examSubjectAnswerVo = new ExamSubjectAnswerVo();
                examCascadeJumpList.forEach(jump -> {
                    if (examSubjectAnswer.getAnswerId().equals(jump.getAnswerId())) {
                        examPaperSubjectList.forEach(e -> {
                            if (e.getSubjectId().equals(jump.getJumpSubject())) {
                                examSubjectAnswerVo.setJump(String.valueOf(e.getSort()));
                            }
                        });
                    }
                });
                List<ExamPaperAnswerVo> paperAnswerVoList = new ArrayList<>();
                List<ExamSubject> subjectList = examSubjectMapper.selectList(Wrappers.lambdaQuery(ExamSubject.class)
                        .eq(ExamSubject::getTenantId, KefuContext.getKefuContext().getTenantId())
                        .eq(ExamSubject::getFatherSubject, examSubjectAnswer.getAnswerId()));
                for (ExamSubject subject : subjectList) {
                    ExamPaperAnswerVo sonActivityPaperInfo = getSonActivityPaperInfo(partnerId, subject, examPaperSubjectList, examCascadeJumpList);
                    paperAnswerVoList.add(sonActivityPaperInfo);
                }
                examSubjectAnswerVo.setAnswerId(examSubjectAnswer.getAnswerId());
                examSubjectAnswerVo.setAnswerContent(examSubjectAnswer.getAnswerContent());
                examSubjectAnswerVo.setSonSubjectList(paperAnswerVoList);
                examSubjectAnswerVoList.add(examSubjectAnswerVo);
            }
            examPaperAnswerVo.setAnswers(examSubjectAnswerVoList);
        }
        return list;
    }

    public ExamPaperAnswerVo getSonActivityPaperInfo(String partnerId, ExamSubject examSubject, List<ExamPaperSubject> examPaperSubjectList, List<ExamCascadeJump> examCascadeJumpList) {
        ExamPaperAnswerVo examPaperAnswerVo = new ExamPaperAnswerVo();
        examPaperAnswerVo.setFatherSubject(examSubject.getFatherSubject());
        examPaperAnswerVo.setSubjectId(examSubject.getSubjectId());
        examPaperAnswerVo.setSubjectContent(examSubject.getSubjectContent());
        examPaperAnswerVo.setTypeName(examSubject.getTypeName());
        List<ExamPaperAnswer> list = examPaperAnswerMapper.selectList(Wrappers.lambdaQuery(ExamPaperAnswer.class)
                .eq(ExamPaperAnswer::getPartnerId, partnerId)
                .eq(ExamPaperAnswer::getSubjectId, examSubject.getSubjectId()));
        List<String> answerList = new ArrayList<>();
        for (ExamPaperAnswer answer : list) {
            if (answer.getAnswerId() != null && !answer.getAnswerId().equals("")) {
                answerList.add(answer.getAnswerId());
            }
            examPaperAnswerVo.setAnswerContent(answer.getAnswerContent());
        }
        examPaperAnswerVo.setAnswerId(answerList);
        List<ExamSubjectAnswer> examSubjectAnswers = examSubjectAnswerMapper.selectList(Wrappers.lambdaQuery(ExamSubjectAnswer.class)
                .eq(ExamSubjectAnswer::getSubjectId, examSubject.getSubjectId())
                .orderByAsc(ExamSubjectAnswer::getAnswerSort));
        List<ExamSubjectAnswerVo> answers = new ArrayList<>();
        examSubjectAnswers.forEach(answer -> {
            ExamSubjectAnswerVo vo = new ExamSubjectAnswerVo();
            vo.setAnswerId(answer.getAnswerId());
            vo.setAnswerContent(answer.getAnswerContent());
            examCascadeJumpList.forEach(jump -> {
                if (answer.getAnswerId().equals(jump.getAnswerId())) {
                    examPaperSubjectList.forEach(paperSubject -> {
                        if (jump.getJumpSubject().equals(paperSubject.getSubjectId())) {
                            vo.setJump(String.valueOf(paperSubject.getSort()));
                        }
                    });
                }
            });
            answers.add(vo);
        });
        examPaperAnswerVo.setAnswers(answers);
        return examPaperAnswerVo;
    }
}
